<template>
	<view class="layout">
		<view class="layout-nav" :style="{ height: fixedTop + 'px' }">
			<DistributionNavBar title="素材下载" fixed rgb="white">
				<template slot="left">
					<image :src="bankIcon" @click="clickBack" />
				</template>
			</DistributionNavBar>
		</view>
		<view class="layout-main">
			<view class="layout-main-fixed" :style="{ marginTop: fixedTop + 'px' }">
				<view class="layout-tabs">
					<ETabs
						@change="tabChange"
						listKey="typeName"
						:current="tabCurrent"
						v-if="initTab"
						:list="typeList"
						line-bottom="1"
						:scaleValue="0.77"
						:font-size="16"
						active-color="#FF6B11"
						scale
						bold
						background="#fff"
						:height="100"
						customNav
					>
						<view slot="tabLine" class="tab-line">
							<image src="/static/icon/icon_sc_xian@3x.png" />
						</view>
					</ETabs>
				</view>
				<view class="layout-type flex row-between col-center" v-if="initTab">
					<view>
						共 {{ typeList[tabCurrent][activeType === 'video' ? 'video' : 'image'] || 0 }}
						{{ activeType === 'video' ? '个' : '张' }}
					</view>
					<view class="format-switch flex">
						<view
							class="format-item"
							:class="{ 'format-active': activeType === item.value }"
							v-for="item in materialTypeArr"
							:key="item.value"
							@click="switchMaterial(item.value)"
						>
							{{ item.label }}
						</view>
					</view>
				</view>
			</view>
			<view class="layout-main-content" :class="{ 'empty-box': true }">
				<template v-if="isSkelett || isResourceListLength">
					<!--  :style="[swiperStyle]"-->
					<swiper class="swiper" skip-hidden-item-layout :current-item-id="tabCurrent" @animationfinish="changeTabsType">
						<swiper-item
							:item-id="index"
							:key="tabItem.typeId"
							v-for="(tabItem, index) in typeList"
							class="layout-main-content-box-item"
						>
							<MaterialDownloadResource
								:disabled="isLoading"
								:isSkelett="isSkelett"
								:isPreview="false"
								:list="materialList[tabCurrent][activeType === 'video' ? 'videoTdMaterials' : 'imgTdMaterials']"
								@openPreview="openPreview"
								@changeResourceListStatus="changeResourceListStatus"
							/>
						</swiper-item>
					</swiper>
				</template>

				<DistributionHint :type="isHintStatus" v-if="isHintStatus === 'nodata'" :customize="hintCustomize" />
			</view>
		</view>

		<CommonMateriaFooter v-show="!isSkelett">
			<template slot="footerButton">
				<view class="has-select flex row-between" v-if="downFileLength">
					<text class="layout-footer-subLable">
						图片已选{{ selectedImageNumber }} / 视频已选{{ selectedVideoNumber }}
						<text v-if="allSizeNum">（共{{ countSize }}）</text>
					</text>
					<text class="cancle-btn" @click="cancleAllSelect">一键取消</text>
				</view>
				<view class="layout-footer">
					<template v-if="!isLoading">
						<button
							:disabled="isSubmitReview || isLoading"
							:class="{
								disabled: isSubmitReview
							}"
							@click="batchFileDownload('new')"
						>
							一键下载至本地相册
						</button>
					</template>
					<template v-else>
						<DownloadProgressBar :list="temporaryStorageList" />
					</template>
				</view>
			</template>
		</CommonMateriaFooter>
		<DistributionResourcePreview
			remote
			frequency
			v-model="isPreviewPopup"
			:list="previewList"
			:index="previewCurrentIndex"
			@changeIndex="changePreviewCurrentIndex"
			:isNewMaterial="true"
		/>
	</view>
</template>
<!-- todo 手机上待验证 -->
<script>
import { debounce } from 'lodash';
import { isIos, getSystemInfo, defaultImageUrl } from '@/utils';
import { getMaterialFileSize, hintUploadAndDownload } from '@/utils/common';

import DistributionHint from '@/components/distributionHint';
import CommonMateriaFooter from './components/CommonMateriaFooter';
import ETabs from '@/components/distributionTabs/ETabs';
import MaterialDownloadResource from './components/MaterialDownloadResource';
import DistributionResourcePreview from '@/components/distributionResourcePreview';
import DownloadProgressBar from './components/DownloadProgressBar';
import DistributionNavBar from '@/components/distributionNavBar/indeHome';
import { materialTypeList, materialAllList, downMaterialRecordUrl } from '@/api/newMaterial';
import EncapsulationDownLoad from '@/plugIn/downLoad';

const bankIcon = Object.freeze(`${defaultImageUrl}help/icon_navbar_back.png`);
const hintBgImageUrl = Object.freeze(`${defaultImageUrl}image/img_nopic.png`);

const hintCustomize = Object.freeze({
	nodata: {
		label: '暂无相关素材内容，敬请期待素材内容更新！',
		imagrUrl: hintBgImageUrl
	}
});

const { itemSize, marginLeft, widthHeight } = getMaterialFileSize();

// 顶部导航 rgba
const speed = 80;
const modelIsIos = isIos();

const { statusBarHeight } = getSystemInfo();
const fixedTop = Object.freeze((modelIsIos ? 44 : 48) + statusBarHeight);
const maxSize = 1024 * 1024 * 500;
export default {
	name: 'MaterialDownload',

	data() {
		this.debounced = debounce((scrollTop) => {
			this.scrollTop = scrollTop;
		}, 10);

		return {
			maxSize,
			fixedTop,
			bankIcon,
			modelIsIos: false,

			hintCustomize,

			scrollTop: 0,
			isSkelett: true,

			tabCurrent: 0,
			productId: null,
			singleMaterialList: [],
			materialResourceList: [],

			requestParams: {
				pageIndex: 1,
				pageSize: 50
			},

			isLoading: false,
			isHintStatus: '', // nomore  nodata

			previewList: [],
			isPreviewPopup: false,
			previewCurrentIndex: 0,

			selectedImageNumber: 0,
			selectedVideoNumber: 0,

			initTab: false,
			typeList: [],
			materialTypeArr: [
				{ label: '图片', value: 'image' },
				{ label: '视频', value: 'video' }
			],
			activeType: 'image',
			materialList: [],
			allResourceObject: [],
			allSizeArr: [],
			isDisabled: false,
			temporaryStorageList: [],
			downRemind: {
				maxSize: '为保证下载速率，单次选择下载素材请不要超过500M！'
			}
		};
	},

	onLoad(option = {}) {
		const { productId = 0, index = 0 } = option;
		this.productId = productId;

		this.tabCurrent = +index;
		// 假数据 119465
		this.getMaterialList(productId);
	},

	created() {
		this.download = new EncapsulationDownLoad({
			that: this
		});
	},
	computed: {
		allSizeNum() {
			// 1 MB = 1024 KB
			const { allSizeArr = [], maxSize, downRemind } = this;
			let computedResult =
				allSizeArr.reduce(function (total, value) {
					return total + value;
				}, 0) || 0;
			if (computedResult > maxSize) {
				uni.showToast({
					title: downRemind?.maxSize || '超出限制',
					icon: 'none',
					duration: 3000
				});
			}

			return computedResult;
		},
		countSize() {
			const { allSizeNum = 0 } = this;
			let sencondResult = allSizeNum / 1024 / 1024;

			if (sencondResult.toFixed(2) < 0.01) {
				return (allSizeNum / 1024).toFixed(2) + 'kb';
			} else {
				return sencondResult.toFixed(2) + 'M';
			}
		},
		isResourceListLength() {
			const { materialList } = this;

			return materialList.length;
		},

		isSubmitReview() {
			const { allResourceObject, allSizeNum, maxSize } = this;

			const formatList = allResourceObject.filter((item) => item.isActive);

			if (!formatList.length) {
				return true;
			}

			let imageNumber = 0;
			let videoNumber = 0;

			formatList.forEach((item) => {
				const { materialType } = item;

				materialType === 2 ? ++videoNumber : ++imageNumber;
			});

			if (allSizeNum > maxSize) {
				return true;
			}

			return false;
		},
		downFileLength() {
			const { selectedImageNumber, selectedVideoNumber } = this;

			return selectedImageNumber + selectedVideoNumber;
		},
		// 暂未用
		swiperStyle() {
			const { isSkelett, isResourceListLength } = this;

			const maxLength = isSkelett ? 2 : Math.ceil((isResourceListLength || 1) / itemSize);

			return {
				height: `${maxLength * (marginLeft + widthHeight)}px`
			};
		},
		isTemporaryStorageList() {
			const { temporaryStorageList } = this;
			const isStatus = !!temporaryStorageList.length;
			return isStatus;
		}
	},

	methods: {
		batchFileDownload(type = 'new') {
			const { allResourceObject } = this;

			this.isDisabled = true;

			const formatList = allResourceObject.filter((item) => item.isActive).map((item) => ({ ...item }));

			this.temporaryStorageList = formatList;
			this.isLoading = true;
			this.download.startDownloadFile(type);
		},
		// 暂未用
		getClassList(param) {
			materialTypeList({ productId: param }).then((res = {}) => {
				const { code = 0, data = [] } = res;
				if (code !== 200) {
					uni.showToast({
						icon: 'none',
						title: '数据错误'
					});
					return;
				}
				this.typeList = data;
			});
		},
		getMaterialList(params = '') {
			const { productId } = this;
			materialAllList({
				productId: params || productId
			}).then((res = {}) => {
				const { code, data = {} } = res;
				console.log(res);
				if (code !== 200) {
					uni.showToast({
						icon: 'none',
						title: '暂无数据'
					});
					return;
				}
				let typeList = [];
				let materialList = [];
				let getData = data || [];
				let allResourceObject = {};

				materialList = getData.map((item = {}) => {
					const { imgTdMaterials = [], typeId = '', typeName = '', videoTdMaterials = [] } = item;
					typeList.push({
						image: imgTdMaterials.length || 0,
						video: videoTdMaterials.length || 0,
						typeId,
						typeName
					});

					return {
						imgTdMaterials,
						videoTdMaterials
					};
				});
				allResourceObject = materialList.map((item) => {
					const { imgTdMaterials = [], videoTdMaterials = [] } = item;
					return [...imgTdMaterials, ...videoTdMaterials];
				});
				this.typeList = typeList;
				
				this.materialList = materialList;
				this.allResourceObject = allResourceObject.flat() || [];

				this.isHintStatus = this.allResourceObject.length ? 'nomore' : 'nodata'; 
				this.$nextTick((e) => {
					this.isSkelett = false;
					this.initTab = true;
				});
			});
		},

		tabChange(current) {
			this.tabCurrent = current;
			this.activeType = 'image';
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
		},
		switchMaterial(val = '') {
			console.log(val);
			this.$set(this, 'activeType', val);
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
		},
		changeTabsType(params) {
			const { tabCurrent } = this;
			const { current } = params.detail;

			if (tabCurrent === current) {
				return;
			}

			this.tabCurrent = current;
		},

		changeResourceListStatus(item = {}) {
			const { id = '' } = item;
			const { selectedImageNumber, selectedVideoNumber, allResourceObject, allSizeNum, maxSize, downRemind = {} } = this;
			let allSizeArr = [];

			const singleItemIndex = allResourceObject.findIndex((item) => item.id === id);
			const singleItem = allResourceObject[singleItemIndex];

			const { kb = 0, materialType = 1 } = singleItem || {};
			const isVideo = materialType === 2;
			let nowSize = allSizeNum + kb;
			if (nowSize > maxSize) {
				uni.showToast({
					title: downRemind?.maxSize || '超出限制',
					icon: 'none',
					duration: 3000
				});
				return;
			}
			this[isVideo ? 'selectedVideoNumber' : 'selectedImageNumber'] =
				(isVideo ? selectedVideoNumber : selectedImageNumber) + (!singleItem.isActive ? 1 : -1);

			this.$set(singleItem, 'isActive', !singleItem.isActive);
			allResourceObject.forEach((item) => {
				if (item.isActive) {
					allSizeArr.push(item.kb);
				}
			});

			this.allSizeArr = allSizeArr;
		},

		openPreview({ previewList, previewCurrentIndex }) {
			this.previewCurrentIndex = previewCurrentIndex;
			this.previewList = previewList;

			this.isPreviewPopup = true;
		},

		changePreviewCurrentIndex(index) {
			this.previewCurrentIndex = index;
		},

		async clickBack() {
			const { isTemporaryStorageList } = this;

			if (!isTemporaryStorageList) {
				uni.navigateBack();
				return;
			}

			const res = await hintUploadAndDownload(false);

			if (!res.confirm) {
				uni.navigateBack();
				this.download.allAbortUpload();
				return;
			}
		},
		allFileDownCallBack() {
			const { temporaryStorageList } = this;

			const successLength = temporaryStorageList.filter((item) => item.status === 'success').length;

			uni.showToast({
				mask: true,
				icon: 'none',
				title: `已成功下载${successLength}个资源。`
			});
			this.isLoading = false;
			this.isDisabled = false;
			this.cancleAllSelect(true);
			// todo 是否切换状态到第一个
		},
		async downRecordAction(params) {
			let result = await downMaterialRecordUrl({ materialIds: params });
			console.log(result);
		},
		cancleAllSelect(isCallBack) {
			const { allResourceObject, downRecordAction } = this;
			let downLoadIds = [];
			allResourceObject.forEach((item) => {
				isCallBack && item.isActive && downLoadIds.push(item.id);
				item.isActive && this.$set(item, 'isActive', false);
			});
			if (isCallBack && downLoadIds.length) {
				downRecordAction(downLoadIds);
			}
			this.selectedImageNumber = 0;
			this.selectedVideoNumber = 0;
			this.allSizeArr = [];
			this.temporaryStorageList = [];
		}
	},

	onPageScroll({ scrollTop }) {
		this.debounced?.(scrollTop);
	},

	components: {
		DistributionHint,
		CommonMateriaFooter,
		MaterialDownloadResource,
		DistributionResourcePreview,
		ETabs,
		DownloadProgressBar,
		DistributionNavBar
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	min-height: 100vh;
	background: #fff;
	@include Db_iosBottomDistance(140rpx);
	position: relative;
	&-nav {
		// margin: 0 -20rpx;

		image {
			width: 40rpx;
			height: 40rpx;
			padding: 20rpx 20rpx 20rpx 0;
		}
	}
	&-main {
		position: relative;
		// margin-top: 20rpx;
		height: calc(100vh - 68px - 200rpx);
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;

		&-fixed {
			position: fixed;
			top: -10rpx;
			left: 0;
			z-index: 9999;
			background: #ffffff;
			width: 100%;
			.layout-tabs {
				height: 100rpx;
			}
			.layout-type {
				font-size: 24rpx;
				color: #666666;
				padding: 20rpx 20rpx 24rpx;
				.format-switch {
					width: 200rpx;
					background: #eeeeee;
					border-radius: 28rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #666666;
					overflow: hidden;
				}
				.format-item {
					padding: 12rpx 0;
					width: 100rpx;
					border-radius: 28rpx;
					text-align: center;
				}
				.format-active {
					background: #ff6b11;
					color: #ffffff;
				}
			}
		}
		.empty-box {
			margin-top: 180rpx;
		}
		&-content {
			height: 100%;
			overflow-y: scroll;
			overflow-x: hidden;
		}
	}

	&-footer {
		display: flex;
		padding: 0 28rpx;

		button {
			flex: 1;
			@include Db_commonButton(80rpx, 24rpx);

			background: #ff6b11;

			&.free-download {
				margin-right: 10rpx;
				background: #fff;
				color: #ff6b11;
				border: 2rpx solid #ff6b11;

				&.disabled {
					color: #fff;
					border-color: #ccc;
					background: #ccc;
				}
			}

			// &:last-child {
			// 	margin-left: 10rpx;
			// }

			&.disabled,
			&.prohibit {
				background: #ccc;
			}

			&.immed-download,
			&.balance-download {
				&.active {
					background: rgba(255, 107, 17, 0.7);
				}

				&.disabled {
					background: #ff6b11;

					&:active {
						background: #ff6b11;
					}
				}
			}
		}

		&-subLable {
			font-size: 22rpx;
		}
	}
}
.tab-line {
	width: 44rpx;
	height: 12rpx;
	display: inline-flex;
	image {
		width: 100%;
		height: 100%;
	}
}
.has-select {
	padding: 0 32rpx 30rpx;
	font-size: 12px;
	color: #666666;
}
.cancle-btn {
	color: #ff6b11;
}
.swiper {
	height: 100%;
}
</style>
